package com.fred.bean

import com.fred.util.KeyManager
import com.fred.util.PropertiesUtil
import com.fred.xlog.Log
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File

private const val KEY_STORE_FILE_NAME = "keyStoreConfig"
data class KeyStoreBean(
    var code:Int = 0,
    var errorMess:String = "",
    var keyStorePath:String = "",
    var keyStorePassword:String = "",
    val alias: ArrayList<KeyStoreAlias> = arrayListOf()
) {
    fun isSuccess() = code == 0
    override fun toString(): String {
        return "KeyStoreBean(code=$code, errorMess='$errorMess', keyStorePath='$keyStorePath', keyStorePassword='$keyStorePassword', alias=$alias)"
    }
}

data class KeyStoreAlias(
    var alias:String = "",
    var password:String = ""
)

data class KeyStoreJson(
    var keyStorePath:String = "",
    var keyStorePassword:String = "",
    var alias:String = "",
    var aliasPassword:String = "",
    var isDefault:Boolean = false
)

data class KeyStores(
    val keyStores:ArrayList<KeyStoreJson> = arrayListOf()
) {
    fun getJson():String {
        val json = Gson().toJson(this)
        return KeyManager.encrypt(json)
//        return Gson().toJson(this)
    }

}

suspend fun getKeyStores():ArrayList<KeyStoreJson> = withContext(Dispatchers.IO) {
    val result = arrayListOf<KeyStoreJson>()
    try {
        val kss = PropertiesUtil.getProperties(KEY_STORE_FILE_NAME,"keyStores")?:""
        Log.i("kss:$kss")
        val json = KeyManager.decrypt(kss)
        val keyStores = Gson().fromJson(json,KeyStores::class.java)?:KeyStores()
        result.addAll(keyStores.keyStores)
    }catch (e:Exception){
        e.printStackTrace()
    }
    result
}

suspend fun saveKeyStores(ksjs:ArrayList<KeyStoreJson>):Boolean = withContext(Dispatchers.IO) {
    try {
        val keyStores = KeyStores()
        keyStores.keyStores.clear()
        keyStores.keyStores.addAll(ksjs)
        PropertiesUtil.setProperties(KEY_STORE_FILE_NAME,"keyStores",keyStores.getJson())
    }catch (e:Exception){
        e.printStackTrace()
        return@withContext false
    }
    true
}

suspend fun addKeyStore(ktj:KeyStoreJson) :Boolean = withContext(Dispatchers.IO){
    try {
        val kss = PropertiesUtil.getProperties(KEY_STORE_FILE_NAME,"keyStores")?:""
        Log.i("kss:$kss")
        val keyStores = Gson().fromJson(kss,KeyStores::class.java)?:KeyStores()
        keyStores.keyStores.add(ktj)
        PropertiesUtil.setProperties(KEY_STORE_FILE_NAME,"keyStores",keyStores.getJson())
    }catch (e:Exception){
        e.printStackTrace()
        return@withContext false
    }
    true
}

//fun main(){
//    val resourcesDir = File(System.getProperty("compose.application.resources.dir"))
//    println("resourcesDir:${resourcesDir.absolutePath}")
//}